package ar.com.photo_admin.service

import ar.com.photo_admin.domain.Message
import ar.com.photo_admin.domain.User
import ar.com.photo_admin.domain.UserMessage

/**
 * Service for domain classes Message and UserMessage
 */
class MessageService {
	
	static transactional = true
	
	def notificationsService

	/**
	 * Sends a message with the given subject and body to a user. 
	 */
	def sendMessage(String subject, String body, User from, User to) {

		Message message = new Message(subject : subject, message : body)
		UserMessage userMessage = new UserMessage(message : message, notified : false)

		from.addToSentMessages(message)
		to.addToReceivedMessages(userMessage)
		
		from.save(flush:true)
		to.save(flush:true)
		
		notificationsService.notifyNewMessage(message, userMessage)
		
		return message
	}
	
	/**
	 * Deletes the messages from the database.
	 */
	def deleteMessage(def messages) {
		
		messages.each { Message message ->
			message = message.refresh()
			
			User from = message.from
			User to = message.userMessage.to
			
			UserMessage userMessage = message.userMessage
			
			to.removeFromReceivedMessages(userMessage)
			from.removeFromSentMessages(message)

			userMessage.delete()
		}
	}
}
